import Taro, {Component, Config, useEffect, useState, useRef} from '@tarojs/taro'
import {View, Text, Image, Button, OpenData, Input, Picker} from '@tarojs/components'
import './index.scss'
import lovelornUser, {
  CipherData,
  MiniProgramRegisterDTO,
  MemberBasicInfoBO,
} from '../../api/lovelorn-user'
import env from '../../utils/env.json'

import {batchData} from '../MyInfo/batch'
import {Cityoption} from '../MyInfo/mapCity'
import {setGlobalData, getGlobalData} from '../../utils/global'

function Login() {
  const [code, setCode] = useState('')
  const [phoneAuth, setPhoneAuth] = useState(false)
  const [phoneDetail, setPhoneDetail] = useState({} as CipherData)
  const [userInfo, setUserInfo] = useState({} as CipherData)
  const [isLogin, setIsLogin] = useState(false)
  const [loadOver, setLoadOver] = useState(false)
  const [maritalStatus, setMaritalStatus] = useState(-1)
  const [maritalText, setMaritalText] = useState('请选择')
  const [gender, setGender] = useState(0)
  const [nickName, setNickName] = useState('')
  const [commitParams, setCommitParams] = useState({} as MemberBasicInfoBO)
  const [path, setPath] = useState('')
  const rangeValue = ['未婚', '离异', '丧偶', '已婚']
  const [noRegitser, setNoRegister] = useState(false)
  const [step1, setStep1] = useState(false)
  const [step2, setStep2] = useState(false)
  const loginVO = useRef({})
  const [multiArray, setMultiArray] = useState([[]])
  const [multiIndex, setMultiIndex] = useState([[]])
  const [height, setHeight] = useState([])
  const [weight, setWeight] = useState([])
  const [statusBarHeight, setStatusBarHeight] = useState(getGlobalData('statusBarHeight') || 20)
  const [navigationHeight, setNavigationHeight] = useState(
    getGlobalData('navigatetionHeight') || 44,
  )
  useEffect(() => {
    let temp = [[]]
    temp = [[...Cityoption], [...Cityoption[0].children]]
    setMultiArray(temp)
    let arr = []
    for (let i = 140; i < 200; i++) {
      arr.push(i + 'CM')
    }
    let weightArr = []
    for (let j = 30; j < 100; j++) {
      weightArr.push(j + 'kg')
    }
    setHeight(arr)
    setWeight(weightArr)
  }, [])
  const maleImg =
    'https://cdn-qa.yryz.com/lovelorn/image/default/202006/651258728521728.png?w=200&h=200'
  const femaleImg =
    'https://cdn-qa.yryz.com/lovelorn/image/default/202006/651258896293888.png?w=200&h=200'
  const [userImg, setUserImg] = useState(maleImg)
  const [animation, setAnimation] = useState(
    Taro.createAnimation({
      duration: 400,
      timingFunction: 'linear',
      delay: 400,
      transformOrigin: 'left top 0',
    }),
  )
  const loginThird = codeData => {
    lovelornUser.action
      .login({
        code: codeData,
      })
      .then(result => {
        console.log(result, 'loginThird')
        if (result && result.checkFlag) {
          Taro.hideLoading()
          console.log('userlogin path', `/${this.$router.params.path}`, this.$router.params.path)
          setGlobalData('loginVO', result.loginVO)
          loginVO.current = result.loginVO
          if (this.$router.params.path) {
            if (
              this.$router.params.path.indexOf('Home') > -1 ||
              this.$router.params.path.indexOf('Mine') > -1
            ) {
              Taro.switchTab({
                url: `/${this.$router.params.path}`,
              })
            } else {
              Taro.redirectTo({
                url: `/${this.$router.params.path}`,
              })
            }
          } else {
            Taro.switchTab({
              url: `/pages/Home/index`,
            })
          }
          Taro.setStorage({
            key: 'isLogin',
            data: true,
          })
          Taro.setStorage({
            key: 'loginVO',
            data: result.loginVO,
          })
        } else {
          Taro.setStorage({
            key: 'isLogin',
            data: false,
          })
          if (result.loginVO) {
            if (result.loginVO && result.loginVO.user.gender == 0) {
              console.log(result.loginVO, 'result.loginVO')
              setGlobalData('loginVO', result.loginVO)
              loginVO.current = result.loginVO
              Taro.hideLoading()
              setNoRegister(true)
              setStep1(true)
            } else {
              setGlobalData('loginVO', result.loginVO)
              Taro.setStorage({
                key: 'loginVO',
                data: result.loginVO,
              })
              Taro.switchTab({
                url: `/pages/Home/index`,
              })
            }
          } else {
            Taro.hideLoading()
          }
        }
      })
  }

  const loginWx = () => {
    return new Promise((resolve, reject) => {
      Taro.login({
        success: res => {
          console.log(res, 'res')
          resolve(loginThird(res.code))
        },
        fail: error => {
          console.log(error, 'error')
          Taro.showToast({
            title: '微信登录失败',
          })
        },
      })
    })
  }

  const changeCity = e => {
    console.log(e.detail.value, 'e')
    console.log(Cityoption[e.detail.value[0]].children[e.detail.value[1]].label)
    setCommitParams(() => {
      return {
        ...commitParams,
        userCity: Cityoption[e.detail.value[0]].children[e.detail.value[1]].label,
        cityCode: Cityoption[e.detail.value[0]].children[e.detail.value[1]].value,
      }
    })
  }

  const changeCloumn = e => {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value)

    const data = {
      multiArray: multiArray,
      multiIndex: multiIndex,
    }
    data.multiIndex[e.detail.column] = e.detail.value
    switch (e.detail.column) {
      case 0:
        data.multiArray[1] = Cityoption[e.detail.value].children
        setMultiArray(data.multiArray)
        setMultiIndex([e.detail.value])
        // setMultiIndex(data.multiIndex)
        break
    }
  }

  const changeHeight = e => {
    setCommitParams(() => {
      return {...commitParams, heigth: height[e.detail.value].replace('CM', '')}
    })
  }
  const renderHeight = e => {
    let reg = new RegExp(/CM/)
    if (e.toString().match(reg)) {
      return e
    } else {
      return e + 'CM'
    }
  }

  const changeWeight = e => {
    setCommitParams(() => {
      return {...commitParams, weight: weight[e.detail.value].replace('kg', '')}
    })
  }
  const renderWeight = e => {
    let reg = new RegExp(/kg/)
    if (e.toString().match(reg)) {
      return e
    } else {
      return e + 'kg'
    }
  }

  const changeEdu = e => {
    setCommitParams(() => {
      return {
        ...commitParams,
        educationBackgroundValue: batchData.sl_education_background[e.detail.value].value,
        educationBackground: batchData.sl_education_background[e.detail.value].key,
      }
    })
  }

  const changeOccupation = e => {
    setCommitParams(() => {
      return {
        ...commitParams,
        occupationValue: batchData.member_career[e.detail.value].value,
        occupation: batchData.member_career[e.detail.value].key,
      }
    })
  }

  const changeMonthly = e => {
    setCommitParams(() => {
      return {
        ...commitParams,
        monthlyProfileValue: batchData.member_monthly_income[e.detail.value].value,
        monthlyProfile: batchData.member_monthly_income[e.detail.value].key,
      }
    })
  }

  useEffect(() => {
    Taro.showLoading({
      title: '登陆中',
      // mask: true,
    })
    loginWx()
  }, [])

  const tobegin = res => {
    console.warn(res, 'res')
    setUserInfo(res.detail)
    if (res.detail && res.detail.userInfo) {
      setPhoneAuth(true)
      setTimeout(() => {
        const slideOut = Taro.createAnimation({
          duration: 300,
          timingFunction: 'linear',
          delay: 100,
          transformOrigin: 'left top 0',
        })
        slideOut.translateX(0).step()
        setAnimation(slideOut.export())
      }, 100)
    }
  }

  const getDateTimeStamp = (dateStr: string) => {
    if (!dateStr) {
      return 0
    }
    return Date.parse(dateStr.replace(/-/gi, '/'))
  }

  const commitStep = () => {
    console.log(commitParams, 'aa')
    if (
      !commitParams.birthday ||
      !commitParams.nickName ||
      (!commitParams.maritalStatus && commitParams.maritalStatus != 0) ||
      commitParams.gender == 0
    ) {
      Taro.showToast({
        title: '请完善基本信息',
        icon: 'none',
      })
      return
    } else if (getDateTimeStamp(commitParams.birthday) > +new Date().getTime()) {
      Taro.showToast({
        title: '请填写正确的出生日期',
        icon: 'none',
      })
    }
    setStep1(false)
    setStep2(true)
  }

  const commitInfo = () => {
    console.error(loginVO.current, 'loginVO.current')
    console.log(commitParams, 'commitParams')
    if (
      (commitParams.userImg && commitParams.userImg.includes('https://cdn')) ||
      userImg.includes('https://cdn')
    ) {
      lovelornUser.memberBasicInfos
        .updateByUserId({
          userImg: commitParams.userImg || userImg,
          ...commitParams,
          // userId: loginVO.current.authInfo.userId,
        })
        .then(result => {
          if (result) {
            console.log('更新用户数据成功')
            Taro.switchTab({
              url: '/pages/Home/index',
            })
          } else {
            Taro.showToast({
              title: `更新失败`,
              icon: 'none',
              duration: 2000,
            })
          }
        })
        .catch(ex => {
          console.log('catch the traffic', JSON.stringify(ex))
          Taro.showToast({
            title: ex.data.msg,
            icon: 'none',
          })
        })
    } else {
      Taro.uploadFile({
        url: `${env.httpBaseUrl}/platform-support/v1.4/pt/uploads/action/upload-image`,
        filePath: userImg,
        name: 'file',
        header: {
          tenantId: 'lovelorn',
          devType: 4,
          userId: loginVO.current.authInfo.userId,
          token: loginVO.current.authInfo.token,
        },
        success: function(res) {
          const resourceUrl = JSON.parse(res.data).data.resourceUrl
          console.log(resourceUrl, 'resourceUrl')
          lovelornUser.memberBasicInfos
            .updateByUserId({
              userImg: resourceUrl,
              ...commitParams,
              // userId: loginVO.current.authInfo.userId,
            })
            .then(result => {
              if (result) {
                console.log('更新用户数据成功')
                Taro.navigateTo({
                  url: '/pages/Home/index',
                })
              } else {
                Taro.showToast({
                  title: '更新失败',
                  icon: 'fail',
                  duration: 2000,
                })
              }
            })
            .catch(ex => {
              console.log('catch the traffic', JSON.stringify(ex))
              Taro.showToast({
                title: ex.data.msg,
                icon: 'none',
              })
            })
        },
        fail: function(ex) {
          console.log(ex)
          Taro.showToast({
            icon: 'none',
            title: '图片上传失败',
          })
        },
        complete(result) {
          console.log(result, 'result')
        },
      })
    }
  }
  const chooseImage = () => {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths, 'tempFilePaths')
        setUserImg(tempFilePaths[0])
      },
    })
  }

  const toGetPhone = res => {
    console.error(res, 'phone')
    if (res.detail && res.detail.encryptedData) {
      const params = res.detail
      let loginCode = ''
      setPhoneDetail(res.detail)
      Taro.login({
        success: result => {
          console.log(result.code)
          loginCode = result.code
          setCode(() => {
            return result.code
          })
          lovelornUser.action
            .register({
              code: loginCode,
              phoneNumber: {
                encryptedData: params.encryptedData,
                iv: params.iv,
              },
              userInfo: {
                encryptedData: userInfo.encryptedData,
                iv: userInfo.iv,
              },
            })
            .then(resData => {
              console.log(resData, 'resdata')
              if (!resData.binding) {
                loginVO.current = resData.loginVO
                setGlobalData('loginVO', resData.loginVO)
                if (resData.loginVO.user.gender == 1) {
                  setUserImg(maleImg)
                } else if (resData.loginVO.user.gender == 2) {
                  setUserImg(femaleImg)
                }
                setNoRegister(() => {
                  return true
                })
                setStep1(true)
                // 未注册 获取token等相关信息 保存用于img上传时候
              }
            })
            .catch(ex => {
              console.log(ex)
            })
        },
      })
    }
  }
  const choiseGender = e => {
    // setGender(e)
    setCommitParams(() => {
      return {...commitParams, gender: e}
    })
  }

  const changeSelect = e => {
    console.log(e.detail.value)
    setMaritalText(rangeValue[e.detail.value])
    setMaritalStatus(e.detail.value)
    setCommitParams(() => {
      return {...commitParams, maritalStatus: e.detail.value}
    })
  }
  const changeDate = e => {
    console.log(e.detail.value, 'e')
    console.log(getDateTimeStamp(e.detail.value))
    if (getDateTimeStamp(e.detail.value) > +new Date().getTime()) {
      Taro.showToast({
        title: '请选择正确的出生日期',
        icon: 'none',
      })
      return
    }
    setCommitParams(() => {
      return {...commitParams, birthday: e.detail.value}
    })
    // setUserData(() => {
    //   return {...userData, birthday: e.detail.value}
    // })
  }

  const changeNickName = (name: string, value: string) => {
    setCommitParams(() => {
      return {...commitParams, [name]: value}
    })
  }

  const renderMonth = id => {
    let res = batchData.member_monthly_income.filter(el => {
      return el.key == id
    })
    return res[0].value
  }

  return (
    <View className="userLoginPage">
      <View
        className="navigationBar"
        style={{height: `${statusBarHeight + navigationHeight}` + 'px'}}>
        <View style={{height: `${statusBarHeight}` + 'px'}}></View>
        <View
          className="flex"
          style={{height: `${navigationHeight}` + 'px'}}
          onClick={() => {
            setStep1(true)
            setStep2(false)
          }}>
          {step2 && noRegitser && !step1 && <Text className="iconfont iconarrow-left"></Text>}
        </View>
      </View>
      {!noRegitser && (
        <View className="loginregist-container">
          <View className="loginregist-content">
            <View className="authorize">
              <View className="avatar">
                {/* <OpenData type="userAvatarUrl" /> */}
                <Image src={require('../../assets/seeking/icon.png')} className="logoAvater" />
              </View>
              <View className="username">
                <OpenData className="username" type="userNickName" />
              </View>
              {!isLogin && (
                <View>
                  {!loadOver && !phoneAuth && (
                    <View>
                      <View className="tips">授权用户登录</View>
                      <View className="btns">
                        <Button
                          className="authorize-btn"
                          openType="getUserInfo"
                          onGetUserInfo={tobegin}>
                          开启授权登录
                        </Button>
                      </View>
                    </View>
                  )}

                  {phoneAuth && (
                    <View animation={animation} className="modleContent modleContentPhone">
                      <View className="tips">授权手机号码</View>
                      <View className="btns">
                        <Button
                          className="authorize-btn"
                          openType="getPhoneNumber"
                          onGetphonenumber={toGetPhone}>
                          确定登录
                        </Button>
                      </View>
                    </View>
                  )}
                </View>
              )}
            </View>
          </View>
        </View>
      )}
      {noRegitser && (
        <View className="regeisterPage">
          {step1 && (
            <View className="step1">
              <View className="chooseImage" onClick={chooseImage}>
                <View className="avatar">
                  <Image className="userImg" src={userImg} />
                </View>
                <View className="avaterTips">点击上传头像</View>
              </View>
              <View className="registerForm">
                <View className="flex alignCenter">
                  <Text className="nickName">昵称</Text>
                  <Input
                    className="inputType"
                    placeholder="请填写你的昵称"
                    onInput={e => {
                      changeNickName('nickName', e.detail.value)
                    }}
                  />
                </View>
                <View className="flex alignCenter">
                  <Text className="nickName">性别</Text>
                  <View className="genderChoise">
                    <View
                      className={commitParams.gender == 1 ? 'leftMale activeMale' : 'leftMale'}
                      onClick={() => {
                        choiseGender(1)
                      }}>
                      {/* <Text className="gender-circle gender-normal"> */}
                      <Text className="iconfont iconmale1"></Text>
                      {/* </Text> */}男
                    </View>
                    <View
                      className={commitParams.gender == 2 ? 'rightMale activeFemale' : 'rightMale'}
                      onClick={() => {
                        choiseGender(2)
                      }}>
                      <Text className="iconfont iconfemale1"></Text>女
                    </View>
                  </View>
                </View>
                <View className="flex alignCenter">
                  <Text className="nickName">婚姻状况</Text>
                  <Picker
                    mode="selector"
                    className="pickerArea"
                    range={rangeValue}
                    onChange={changeSelect}>
                    <View className="pickerValue">
                      {maritalText}
                      <Text className="iconfont iconarrow-right"></Text>
                    </View>
                  </Picker>
                </View>
                <View className="flex alignCenter" style={{borderBottom: 0}}>
                  <Text className="nickName">出生日期</Text>
                  <Picker
                    mode="date"
                    className="pickerArea"
                    headerText="选择出身日期"
                    onChange={changeDate}>
                    {commitParams.birthday ? commitParams.birthday : '请选择'}
                    <Text className="iconfont iconarrow-right"></Text>
                  </Picker>
                </View>
              </View>
              <View className="loginSubmit loginComfirm" onClick={commitStep}>
                <Text>下一步</Text>
              </View>
            </View>
          )}
          {step2 && (
            <View>
              <View className="registerForm">
                <View className="flex alignCenter">
                  <Text className="nickName">身高</Text>
                  <Picker
                    mode="selector"
                    className="pickerArea"
                    range={height}
                    onChange={changeHeight}>
                    {commitParams.heigth != null ? renderHeight(commitParams.heigth) : ''}
                    <Text className="iconfont iconarrow-right"></Text>
                  </Picker>
                </View>

                <View className="flex alignCenter">
                  <Text className="nickName">学历</Text>
                  <Picker
                    className="pickerArea"
                    mode="selector"
                    range={batchData.sl_education_background}
                    onChange={changeEdu}
                    rangeKey="value">
                    {commitParams.educationBackgroundValue != null
                      ? commitParams.educationBackgroundValue
                      : ''}
                    <Text className="iconfont iconarrow-right"></Text>
                  </Picker>
                </View>

                <View className="flex alignCenter">
                  <Text className="nickName">职业</Text>
                  <Picker
                    className="pickerArea"
                    mode="selector"
                    range={batchData.member_career}
                    onChange={changeOccupation}
                    rangeKey="value">
                    {commitParams.occupationValue != null ? commitParams.occupationValue : ''}
                    <Text className="iconfont iconarrow-right"></Text>
                  </Picker>
                </View>

                <View className="flex alignCenter">
                  <Text className="nickName">月收入</Text>
                  <Picker
                    className="pickerArea"
                    mode="selector"
                    range={batchData.member_monthly_income}
                    onChange={changeMonthly}
                    rangeKey="value">
                    {commitParams.monthlyProfile != null
                      ? renderMonth(commitParams.monthlyProfile)
                      : ''}
                    <Text className="iconfont iconarrow-right"></Text>
                  </Picker>
                </View>

                <View className="flex alignCenter">
                  <Text className="nickName">所在地</Text>
                  <Picker
                    className="pickerArea"
                    mode="multiSelector"
                    value={multiIndex}
                    range={multiArray}
                    onChange={changeCity}
                    onColumnChange={changeCloumn}
                    rangeKey="label">
                    {commitParams.userCity ? commitParams.userCity : ''}
                    <Text className="iconfont iconarrow-right"></Text>
                  </Picker>
                </View>
              </View>
              <View className="loginSubmit loginComfirm" onClick={commitInfo}>
                <Text>提交</Text>
              </View>
            </View>
          )}
        </View>
      )}
    </View>
  )
}
Login.config = {
  navigationBarTitleText: '登录',
  navigationBarBackgroundColor: '#fff',
  navigationBarColor: '#000',
  navigationStyle: 'custom',
}
export default Login
